<template>
  <div class="matching-page">
    <div class="matching-header">
      <button class="back-button" @click="goHome">
        <span class="back-icon">←</span>
      </button>
      <h1 class="header-title">匹配</h1>
    </div>

    <div v-if="!isBattleActive" class="matching-content">
      <!-- Team selection view -->
      <div class="team-selection">
        <h2 class="section-title">你的队伍</h2>
        <div class="pokemon-grid">
          <div
              v-for="pokemon in playerTeam"
              :key="pokemon.id"
              class="pokemon-card"
          >
            <div class="pokemon-card-content">
              <img
                  :src="`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png`"
                  :alt="pokemon.name"
                  class="pokemon-thumbnail"
              />
              <h3 class="pokemon-card-name">{{ pokemon.name }}</h3>
              <div>
                <div class="type-badges">
                  <span
                      v-for="(type, index) in pokemon.type.split('/')"
                      :key="index"
                      class="type-badge"
                      :style="{ backgroundColor: getTypeColor(type) }"
                  >
                    {{ type }}
                  </span>
                </div>
                <p class="pokemon-level">Lv. {{ pokemon.level }}</p>
              </div>

            </div>
          </div>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 20px;">
          <button class="start-match-button" @click="startMatch">开始匹配</button>
        </div>
      </div>

    </div>

    <div class="battle-page" v-if="isBattleActive">
      <!-- Battle view -->
      <Battle
          :player-pokemon="playerPokemons"
          :opponent-pokemon="opponentPokemons"
          @battle-end="endBattle"
      />
    </div>

  </div>
</template>

<script setup>
import {ref, inject, onMounted, nextTick} from 'vue';
import Battle from './Battle.vue';
import pokemon_enService from '@/api/services/pokemon_enService';
import movesService from '@/api/services/movesService';
import {typeColorMap, typeMap} from '@/api/constants';

// Helper function to calculate Pokémon stats
const calculateStat = (base, level, iv = 15, ev = 0, isHp = false) => {
  const basePart = Math.floor(((2 * base + iv + Math.floor(ev / 4)) * level) / 100);
  return isHp ? basePart + level + 10 : basePart + 5;
};

const navigate = inject('navigate');
const myPokemon = inject('myPokemon');
const items = inject('items');

const playerTeam = ref([]);
const opponentTeam = ref([]);
const playerPokemons = ref([]);
const opponentPokemons = ref([]);
const isBattleActive = ref(false);

const goHome = () => {
  navigate('home');
};

const fetchPokemonData = async (id) => {
  try {
    const pokemonResponse = await pokemon_enService.getPokemonById(id);
    const types = pokemonResponse.types
        .map(t => typeMap[t.type.name.toLowerCase()] || t.type.name)
        .join('/');
    const stats = pokemonResponse.stats.reduce((acc, stat) => {
      acc[stat.stat.name] = stat.base_stat;
      return acc;
    }, {});
    const level = Math.floor(Math.random() * 5) + 1;

    const moves = pokemonResponse.moves.slice(0, 4).map(move => ({
      id: move.move.url.split('/').slice(-2, -1)[0]
    }));

    const moveDetails = await Promise.all(
        moves.map(async (move) => {
          try {
            const moveResponse = await movesService.getMoveById(move.id);
            return {
              name: moveResponse.name_zh,
              type: typeMap[moveResponse.type.toLowerCase()] || moveResponse.type,
              pp: 25
            };
          } catch (error) {
            return {name: '撞击', type: '一般', pp: 35};
          }
        })
    );

    return {
      id: pokemonResponse.id,
      name: pokemonResponse.name,
      type: types,
      level,
      hp: calculateStat(stats.hp || 50, level, 15, 0, true),
      maxHp: calculateStat(stats.hp || 50, level, 15, 0, true),
      attack: calculateStat(stats.attack || 50, level),
      defense: calculateStat(stats.defense || 50, level),
      speed: calculateStat(stats.speed || 50, level),
      moves: moveDetails.length > 0 ? moveDetails : [{name: '撞击', type: '一般', pp: 35}]
    };
  } catch (error) {
    console.error(`Error fetching Pokémon ${id}:`, error);
    return null;
  }
};

const startMatch = async () => {
  const playerPokemonsData = myPokemon.value.slice(0, 3);
  if (playerPokemonsData.length === 0) {
    alert('你的背包中没有宝可梦，无法开始匹配！');
    return;
  }
  console.log('Player Pokémon set in startMatch:', playerPokemonsData);
  playerPokemons.value = playerPokemonsData;

  const opponentIds = [];
  while (opponentIds.length < 3) {
    const randomId = Math.floor(Math.random() * 151) + 1;
    if (!opponentIds.includes(randomId)) opponentIds.push(randomId);
  }
  const opponentPokemonsData = (await Promise.all(opponentIds.map(fetchPokemonData)))
      .filter(pokemon => pokemon !== null);
  if (opponentPokemonsData.length === 0) {
    alert('无法获取对手宝可梦，请重试。');
    return;
  }
  console.log('Opponent Pokémon set in startMatch:', opponentPokemonsData);
  opponentPokemons.value = opponentPokemonsData;

  isBattleActive.value = true;
};

const endBattle = () => {
  isBattleActive.value = false;
  playerPokemons.value = [];
  opponentPokemons.value = [];
};

const getTypeColor = (type) => {
  return typeColorMap[type] || '#9e9e9e';
};

onMounted(() => {
  playerTeam.value = myPokemon.value.slice(0, 3);
});
</script>

<style scoped>
.matching-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, #e0f7fa, #b2ebf2);
}

.battle-page {
  padding: 16px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.matching-header {
  background-color: #333;
  color: white;
  padding: 16px;
  display: flex;
  align-items: center;
}

.back-button {
  background: none;
  color: white;
  margin-right: 16px;
  padding: 8px;
}

.back-icon {
  font-size: 24px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.matching-content {
  padding: 16px;
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.team-selection {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
  width: 100%;
  max-width: 600px;
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.pokemon-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.pokemon-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.2s, box-shadow 0.2s;
}

.pokemon-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pokemon-card-content {
  text-align: center;
}

.pokemon-thumbnail {
  width: 80px;
  height: 80px;
}

.pokemon-card-name {
  font-weight: 500;
  margin: 8px 0;
  font-size: 14px;
}

.pokemon-level {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.start-match-button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 24px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.1s;
}

.start-match-button:hover {
  background-color: #45a049;
  transform: translateY(-2px);
}

.start-match-button:active {
  transform: translateY(0);
}

.type-badges {
  display: inline-flex;
  gap: 4px;
  margin-bottom: 4px;
}

.type-badge {
  font-size: 12px;
  padding: 2px 8px;
  font-weight: 600;
  border-radius: 12px;
  color: white;
}

</style>